//
//  MessageViewController.swift
//  jiaoyi
//
//  Created by wjk on 2018/9/10.
//  Copyright © 2018年 wjk. All rights reserved.
//

import UIKit
import MJRefresh
import Moya

class MessageViewController: UIViewController,UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!
    
    var type:Int = 1//1、消息；2、公告
    
    var data : NSMutableArray = []
    
    var page : Int = 1;
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我的消息"
        if self.type == 2 {
            self.title = "公告"
        }
        tableView.register(R.nib.homeTableViewCell(),forCellReuseIdentifier : "homeTableViewCell");
        tableView.rowHeight = UITableViewAutomaticDimension;
        reftreshData()
        loadData()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "homeTableViewCell") as! HomeTableViewCell
        let data2 = jsonFormater(data:data[indexPath.row])
        if self.type == 2 {
            cell.labelTitle.text = data2["title"].stringValue
            cell.imgRead.isHidden = data2["read_status"].boolValue
        }else {
            cell.labelTitle.text = "\(data2["title"].stringValue) \n \(data2["content"].stringValue)"
            if data2["read_at"].stringValue.isEmpty {
                cell.imgRead.isHidden = false
            }else {
                cell.imgRead.isHidden = true
            }
        }
        cell.labelDate.text = data2["created_at"].stringValue
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let data2 = jsonFormater(data:data[indexPath.row])
        if self.type == 2 {
            var d = jsonFormater(data: data[indexPath.row])
//            d["read_at"] = "123"
            d["read_status"] = true
            data[indexPath.row] = d
        }else {
            var d = data[indexPath.row] as! [String:Any]
            d["read_at"] = "123"
            d["read_status"] = true
            data[indexPath.row] = d
        }
        
        
        self.tableView.reloadData()
        if self.type == 2 {
            
            NetWorkRequest(.bulletin_id(id:data2["id"].stringValue)) { (res) -> (Void) in
                if res["code"] as! String == "000000" {
                    let vc = MsgDescViewController()
                    vc.bulletin_id = data2["id"].stringValue
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
            
        }else {
            
            NetWorkRequest(.message_id(id: data2["id"].stringValue)) { (res) -> (Void) in
                let jd = jsonFormater(data: res)
                if jd["code"].stringValue == "000000" {
                    
                    let vc = NoticeDesViewController()
                    vc.msgId = data2["id"].stringValue
                    self.navigationController?.pushViewController(vc, animated: true)
                    
                }
            }
            
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension MessageViewController {
    
    fileprivate func reftreshData()  {
        
        tableView.mj_footer = MJRefreshBackNormalFooter {[weak self] in
            
            self?.loadData()
        }
        tableView.mj_header = MJRefreshNormalHeader {[weak self] in
            self?.page = 1;
            self?.loadData()
        }
        
    }
}
extension MessageViewController {
    func loadData() -> Void {
        
        if type == 2 {//获取公告
            
            NetWorkRequest(.bulletin(param: ["page":page,"per_page":AppConstants.pre_count])) {(res) -> (Void) in
                let js = jsonFormater(data: res)
                if js["code"].stringValue == "000000" {
                    let arr = jsonFormater(data: js["data"])["data"].arrayValue as NSArray
                    if self.page <= 1 {
                        self.data = arr.mutableCopy() as! NSMutableArray
                    }else {
                        self.data.addObjects(from: arr as! [Any])
                    }
                                                            
                    self.tableView.reloadData()
                    self.page = self.page + 1
                    if arr.count < AppConstants.pre_count {
                        self.tableView.mj_footer.isHidden = true
                    }else {
                        self.tableView.mj_footer.isHidden = false
                    }
                }
            }
            
            return
        }
        
        MoyaProvider<UserService>().request(UserService.message(page: page, per_page: AppConstants.pre_count)) { (result) in
            switch result {
            case let .success(response) :
                
                let data2 = try? response.mapJSON() as! NSDictionary
                let code = data2!["code"] as! NSString
                if code == "000000" {
                    let data3 = data2!["data"] as? NSDictionary
                    
                    if self.page <= 1 {
                        self.data = (data3?["data"] as! NSArray).mutableCopy() as! NSMutableArray
                    }else {
                        self.data.addObjects(from: (data3?["data"] as! NSArray) as! [Any])
                    }
                    
                    self.tableView.reloadData()
                    self.page = self.page + 1
                    
                    if (data3?["data"] as! NSArray).count < AppConstants.pre_count {
                        self.tableView.mj_footer.isHidden = true
                    }else {
                        self.tableView.mj_footer.isHidden = false
                    }
                }else {
                    showMessage(view: self.view, message: data2!["message"] as! String)
                }
                self.tableView.mj_header.endRefreshing()
                self.tableView.mj_footer.endRefreshing()
                break
            case let .failure(error):
                self.tableView.mj_header.endRefreshing()
                self.tableView.mj_footer.endRefreshing()
                break
            }
        }
    }
}

